import { Dropdown, DropdownItem } from "@/ui/Dropdown/Dropdown";
import cls from "@/styles/components/CreateUser/RoleSelector.module.scss";
import React, { useEffect, useState } from "react";
import { Icon } from "@/ui/Icons/Icon";
import cn from "classnames";
import { OptionI } from "@/models/common";

type Props = {
  setYear: (v: OptionI) => void;
};

const options = [
  { id: "2019", name: "2019" },
  { id: "2020", name: "2020" },
  { id: "2021", name: "2021" },
  { id: "2022", name: "2022" },
  { id: "2023", name: "2023" },
  { id: "2024", name: "2024" },
];

export const YearSelector = ({ setYear }: Props) => {
  const [roleDropdownOpen, setRoleDropdownOpen] = useState(false);
  const [selected, setSelected] = useState<OptionI>(
    options.find((o) => o.id === "2024")
  );

  useEffect(() => {
    if (!selected) return;
    setYear(selected);
  }, [selected]);

  const toggleOpen = () => {
    setRoleDropdownOpen(!roleDropdownOpen);
  };

  return (
    <div className={cls.root}>
      <div className={cls.label}>Год</div>
      <div className={cls.valueBox} onClick={() => toggleOpen()}>
        <div className={cls.value}>{selected?.name}</div>
        <button
          type="button"
          onClick={() => toggleOpen()}
          className={cls.arrow}
        >
          <Icon name="arrow" />
        </button>
      </div>
      <Dropdown
        isOpen={roleDropdownOpen}
        close={() => setRoleDropdownOpen(false)}
        parentCls={cls.root}
        fullWidth
      >
        {options?.map((o) => {
          return (
            <DropdownItem key={o.id}>
              <button
                type="button"
                className={cn(cls.option, {
                  [cls.selected]: o.id === selected?.id,
                })}
                onClick={() => {
                  setSelected(o);
                  setRoleDropdownOpen(false);
                }}
              >
                {o.name}
              </button>
            </DropdownItem>
          );
        })}
      </Dropdown>
    </div>
  );
};
